package com.example.micro_property_springboot.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.micro_property_springboot.mapper.UserMapper;
import com.example.micro_property_springboot.pojo.DTO.user.PasswordDTO;
import com.example.micro_property_springboot.pojo.DTO.user.PersonalDTO;
import com.example.micro_property_springboot.pojo.DTO.user.UserDTO;
import com.example.micro_property_springboot.pojo.SysUser;
import com.example.micro_property_springboot.pojo.VO.PageResult;
import com.example.micro_property_springboot.pojo.VO.Result;
import com.example.micro_property_springboot.pojo.VO.UserVO;
import com.example.micro_property_springboot.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser> implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 登录
     */
    @Override
    public Result<UserVO> login(UserDTO user) {
        //校验非空
        if(user.getUserName()==null||user.getPassword()==null){
            return Result.error("用户名或密码不能为空");
        }
        //查询用户
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName,user.getUserName());
        SysUser selectUser = this.userMapper.selectOne(wrapper);
        //验证是否查询到用户信息
        if(selectUser == null){
            return  Result.error("账号或密码错误");
        }
        if(!selectUser.getPassword().equals(user.getPassword())){
            return Result.error("账号或密码错误");
        }

        if(selectUser.getStatus()==0){
            return Result.error("账号未审核,请等待管理员审核");
        }

        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(selectUser,userVO);
        userVO.setCreateTime(selectUser.getCreateTime().toString());
        userVO.setUpdateTime(selectUser.getUpdateTime().toString());
        userVO.setStatus(selectUser.getStatus() == 1 ? "正常" : "禁用");
        return Result.success(userVO);
    }

    /**
     * 注册
     */
    @Override
    public Result<Void> register(SysUser user) {
        user.setCreateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        user.setUpdateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        user.setStatus(0);
        return this.save(user) ? Result.success("注册成功"):Result.error("注册失败");
    }

    /**
     *修改个人信息
     */
    @Override
    public Result<Void> updateUserPersonal(Long Id, PersonalDTO personalDTO) {
        if(Id == null){
            return Result.error("用户ID不能为空");
        }
        SysUser user = userMapper.selectById(Id);
        if(user == null){
            return Result.error("未找到该用户");
        }

        if(personalDTO.getUserName()!=null){
            user.setUserName(personalDTO.getUserName());
        }
        if(personalDTO.getRealName()!=null){
            user.setRealName(personalDTO.getRealName());
        }
        if(personalDTO.getPhone()!=null){
            user.setPhone(personalDTO.getPhone());
        }
        if(personalDTO.getDeptId()!=null){
            user.setDeptId(personalDTO.getDeptId());
        }
        if(personalDTO.getEmail()!=null){
            user.setEmail(personalDTO.getEmail());
        }

        user.setUpdateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        int rows = userMapper.updateById(user);
        return rows > 0 ? Result.success("修改成功"):Result.error("修改失败");
    }

    /**
     * 修改密码
     */
    @Override
    public Result<Void> updateUserPassword(Long Id, PasswordDTO passwordDTO) {
        if(Id == null){
            return Result.error("用户ID不能为空");
        }

        SysUser user = userMapper.selectById(Id);
        if(user == null){
            return Result.error("未找到该用户");
        }

        if(passwordDTO.getPassword()==null || passwordDTO.getNewPassword()==null){
            return Result.error("原密码或新密码不能为空");
        }

        if(!passwordDTO.getNewPassword().equals(passwordDTO.getConfirmPassword())){
            return Result.error("新密码与确认密码不一致");
        }

        if(!passwordDTO.getPassword().equals(user.getPassword())){
            return Result.error("原密码不正确");
        }

        user.setPassword(passwordDTO.getNewPassword());
        user.setUpdateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        int rows = userMapper.updateById(user);
        return rows > 0 ? Result.success("修改成功"):Result.error("修改失败");
    }


    /**
     * 管理员审核注册
     */
    @Override
    public Result<Void> passUser(Long id) {
        if(id == null){
            return Result.error("用户ID不能为空");
        }

        SysUser user = userMapper.selectById(id);
        if(user == null){
            return Result.error("未找到该用户");
        }

        if(user.getStatus() == 1){
            return Result.error("该用户已通过审核");
        }

        user.setStatus(1);
        user.setUpdateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        int rows = userMapper.updateById(user);
        return rows > 0 ? Result.success("审核通过"):Result.error("审核失败");
    }

    /**
     * 待审核的用户分页
     */
    @Override
    public Result<PageResult<UserVO>> pagePassUser(Integer pageNum, Integer pageSize) {
        //分页查询status=0的用户
        if (pageNum == null || pageSize == null){
            return Result.error("分页参数不能为空");
        }
        Page<SysUser> page = new Page<>(pageNum,pageSize);

        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getStatus,0);
        wrapper.orderByDesc(SysUser::getCreateTime);
        Page<SysUser> userPage = this.userMapper.selectPage(page, wrapper);

        List<UserVO> userVOList = userPage.getRecords().stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user,userVO);
            userVO.setCreateTime(user.getCreateTime().toString());
            userVO.setUpdateTime(user.getUpdateTime().toString());
            userVO.setStatus("待审核");
            userVO.setDeptName("");
            return userVO;
        }).collect(Collectors.toList());

        PageResult<UserVO> pageResult = new PageResult<>();
        pageResult.setTotal(userPage.getTotal());
        pageResult.setRows(userVOList);

        return Result.success(pageResult);
    }

    /**
     * 已审核通过的用户分页
     */
    @Override
    public Result<PageResult<UserVO>> pagePassedUser(Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageSize == null){
            return Result.error("分页参数不能为空");
        }
        Page<SysUser> page = new Page<>(pageNum,pageSize);

        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getStatus,1);
        wrapper.orderByAsc(SysUser::getCreateTime);
        Page<SysUser> userPage = this.userMapper.selectPage(page, wrapper);

        List<UserVO> userVOList = userPage.getRecords().stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user,userVO);
            userVO.setCreateTime(user.getCreateTime().toString());
            userVO.setUpdateTime(user.getUpdateTime().toString());
            userVO.setStatus("正常");
            userVO.setDeptName("");
            return userVO;
        }).collect(Collectors.toList());

        PageResult<UserVO> pageResult = new PageResult<>();
        pageResult.setTotal(userPage.getTotal());
        pageResult.setRows(userVOList);

        return Result.success(pageResult);
    }

    /**
     * 查询所有用户分页
     */
    @Override
    public Result<PageResult<UserVO>> pageAllUser(Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageSize == null){
            return Result.error("分页参数不能为空");
        }
        Page<SysUser> page = new Page<>(pageNum,pageSize);

        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(SysUser::getCreateTime);
        Page<SysUser> userPage = this.userMapper.selectPage(page, wrapper);

        List<UserVO> userVOList = userPage.getRecords().stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user,userVO);
            userVO.setCreateTime(user.getCreateTime().toString());
            userVO.setUpdateTime(user.getUpdateTime().toString());
            userVO.setStatus(user.getStatus() == 0 ? "待审核" : "正常");
            userVO.setDeptName("");
            return userVO;
        }).collect(Collectors.toList());

        PageResult<UserVO> pageResult = new PageResult<>();
        pageResult.setTotal(userPage.getTotal());
        pageResult.setRows(userVOList);

        return Result.success(pageResult);
    }

    /**
     *添加用户
     */
    @Override
    public Result<Void> addUser(SysUser user) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName,user.getUserName());
        SysUser existUser = this.userMapper.selectOne(wrapper);
        if (existUser != null){
            return Result.error("用户名已存在");
        }

        user.setCreateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        user.setUpdateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        user.setStatus(1);

        boolean isSuccess = this.save(user);
        return isSuccess ? Result.success("添加用户成功") : Result.error("添加用户失败");
    }

    /**
     * 删除用户
     */
    @Override
    public Result<Void> deleteUser(Long id) {
        if( id == null){
            return Result.error("用户id不能为空");
        }

        SysUser user = userMapper.selectById(id);
        if (user == null){
            return Result.error("用户不存在");
        }

        int rows = userMapper.deleteById(id);
        return rows > 0 ? Result.success("删除用户成功") : Result.error("删除用户失败");
    }


}
